const app = getApp();
var imgBaseUrl = app.globalData.imgBaseUrl;
var imgPreUrl = app.globalData.imgPreUrl;
Page({
  data: {
    imgBaseUrl: imgBaseUrl,
    imgPreUrl: imgPreUrl,
    userid:app.globalData.userid,
    tabStatus: [0,2,1,3,4],//数据库对应的状态字段
    kong:"",
    orders:[],
    kongbg: imgBaseUrl+"/order_kong.png",
    page:1,
    array: ["微信支付","余额支付(优先余额抵扣)"],
    arrayIndex:0,
    zftype:0,
    orderStatus: ["", "去付款", "待发货", "确认收货", "已签收"],
    titleName: ["", "待付款", "待发货", "配送中", "已完成"],
    page:1,
    clickpay:true
  },
  onLoad:function(options){
    var that=this;
    if(options.status){
      wx.setNavigationBarTitle({
        title: that.data.titleName[options.status],
      })
      this.setData({
        status:options.status
      })
    }
  },
  onShow: function () {
    if(this.data.status){
      this.reqData11();
    }else{
      this.reqData1();        
    }
  },
  reqData1(pull){
    var that = this;
    app.func.postReq('/text/index.php/home/productzf/myproorder', {p:1}, function (res) {
      console.log(res);
      var nodata=false;
      if (res.orders) {
        nodata = res.orders.length > 4 && res.orders.length<20?true:false;
        for (let i = 0, len = res.orders.length; i < len; i++) {
          if (res.orders[i].status >1 && res.orders[i].status < 4) {
            var time = parseFloat(res.orders[i].create_time) + 3600 - (Math.round(new Date().getTime() / 1000));
            res.orders[i].djstime = time;
            res.orders[i].time = that.timeZh(res.orders[i].djstime);
            console.log(i, res.orders[i].djstime);
            if (time > 0) {
              var timer = setInterval(function () {
                res.orders[i].djstime-=1;
                // console.log(i,'倒计时',res.orders[i].djstime,);
                if (res.orders[i].djstime < 0) {
                  clearInterval(res.orders[i].timer);
                }
                that.setData({
                  [`orders[${i}].time`]: that.timeZh(res.orders[i].djstime),
                  [`orders[${i}].djstime`]: res.orders[i].djstime
                })
              }, 1000);
              res.orders[i].timer = timer;
            } else {
              res.orders[i].time =''
            }
          }
        }
        that.setData({
          orders: res.orders,
          money:parseFloat(res.user.money),
          product: res.product,
          page:2,
          readMore:true,
          nodata:nodata
        })
      }else{
        that.setData({
          orders:null
        })
      }
      if(pull){
        var timeout=setTimeout(function(){
          clearTimeout(timeout);
          wx.stopPullDownRefresh();
        },1000)
      }

    })
  },
  reqData2() {
    var that = this;
    var orders=this.data.orders;
    var product = this.data.product;
    var page=that.data.page;
    app.func.postReq('/text/index.php/home/productzf/myproordermore', { p: page }, function (res) {
      var nodata = true,readMore=false;
      if (res.orders) {
        nodata = res.orders.length < 20 ? true : false;
        readMore=res.orders.length<20?false:true;
        for (let i = 0, len = res.orders.length; i < len; i++) {
          if (res.orders[i].status > 1 && res.orders[i].status < 4) {
            var time = parseFloat(res.orders[i].create_time) + 3600 - (Math.round(new Date().getTime() / 1000));
            res.orders[i].djstime = time;
            res.orders[i].time = that.timeZh(res.orders[i].djstime);
            if (time > 0) {
              var timer = setInterval(function () {
                res.orders[i].djstime -= 1;
                if (res.orders[i].djstime < 0) {
                  clearInterval(res.orders[i].timer);
                }
                that.setData({
                  [`orders[${i}].time`]: that.timeZh(res.orders[i].djstime),
                  [`orders[${i}].djstime`]: res.orders[i].djstime
                })
              }, 1000);
              res.orders[i].timer = timer;
            } else {
              res.orders[i].time = ''
            }
          }
        }
        orders=orders.concat(res.orders);  
        product = product.concat(res.product);  
      }
      that.setData({
        orders: orders,
        product: product,
        page: ++page,
        nodata: nodata,
        readMore: readMore,
        loadHidden:false
      })
    })
  },
  reqData11(pull) {
    var that = this;
    app.func.postReq('/text/index.php/home/productzf/oneorder', { otype:that.data.status,p: 1 }, function (res) {
      console.log(res);
      var nodata = false;
      if (res.orders) {
        nodata = res.orders.length > 4 && res.orders.length < 20 ? true : false;
        for (let i = 0, len = res.orders.length; i < len; i++) {
          if (res.orders[i].status > 1 && res.orders[i].status < 4) {
            var time = parseFloat(res.orders[i].create_time) + 3600 - (Math.round(new Date().getTime() / 1000));
            res.orders[i].djstime = time;
            res.orders[i].time = that.timeZh(res.orders[i].djstime);
            console.log(i, res.orders[i].djstime);
            if (time > 0) {
              var timer = setInterval(function () {
                res.orders[i].djstime -= 1;
                // console.log(i,'倒计时',res.orders[i].djstime,);
                if (res.orders[i].djstime < 0) {
                  clearInterval(res.orders[i].timer);
                }
                that.setData({
                  [`orders[${i}].time`]: that.timeZh(res.orders[i].djstime),
                  [`orders[${i}].djstime`]: res.orders[i].djstime
                })
              }, 1000);
              res.orders[i].timer = timer;
            } else {
              res.orders[i].time = ''
            }
          }
        }
        that.setData({
          orders: res.orders,
          product: res.product,
          money:parseFloat(res.user.money),
          page: 2,
          readMore: true,
          nodata: nodata
        })
      } else {
        that.setData({
          orders: null
        })
      }
      if (pull) {
        var timeout = setTimeout(function () {
          clearTimeout(timeout);
          wx.stopPullDownRefresh();
        }, 1000)
      }

    })
  },
  reqData21() {
    var that = this;
    var orders = this.data.orders;
    var product = this.data.product;
    var page = that.data.page;
    app.func.postReq('/text/index.php/home/productzf/oneorder', { otype: that.data.status,p: page }, function (res) {
      var nodata = true, readMore = false;
      if (res.orders) {
        nodata = res.orders.length < 20 ? true : false;
        readMore = res.orders.length < 20 ? false : true;
        for (let i = 0, len = res.orders.length; i < len; i++) {
          if (res.orders[i].status > 1 && res.orders[i].status < 4) {
            var time = parseFloat(res.orders[i].create_time) + 3600 - (Math.round(new Date().getTime() / 1000));
            res.orders[i].djstime = time;
            res.orders[i].time = that.timeZh(res.orders[i].djstime);
            if (time > 0) {
              var timer = setInterval(function () {
                res.orders[i].djstime -= 1;
                if (res.orders[i].djstime < 0) {
                  clearInterval(res.orders[i].timer);
                }
                that.setData({
                  [`orders[${i}].time`]: that.timeZh(res.orders[i].djstime),
                  [`orders[${i}].djstime`]: res.orders[i].djstime
                })
              }, 1000);
              res.orders[i].timer = timer;
            } else {
              res.orders[i].time = ''
            }
          }
        }
        orders = orders.concat(res.orders);
        product = product.concat(res.product);
      }
      that.setData({
        orders: orders,
        product: product,
        page: ++page,
        nodata: nodata,
        readMore: readMore,
        loadHidden: false
      })
    })
  },
  onHide:function(){
    this.clearTimer();
  },
  onUnload:function(){
    this.clearTimer();
  },
  clearTimer:function(){
    var orders = this.data.orders;
    for (let i = 0, len = orders.length; i < len; i++) {
      clearInterval(orders[i].timer);
      console.log('清除', orders[i].timer);
    }
  },
  timeZh:function(time){
    var str='';
    if(time>0){
      var h = Math.floor(time / 3600);
      var m = Math.floor(time / 60 % 60);
      var s = Math.floor(time % 60);
      h = h >= 10 ? h : '0' + h;
      m = m >= 10 ? m : '0' + m;
      s = s >= 10 ? s : '0' + s;
      str = h + ':' + m + ':' + s;
    }
    return str;
  },
  bindShouhuo:function(e){
    var that=this;
    var orders = that.data.orders;
    var {id,index,time}=e.currentTarget.dataset;
    wx.showModal({
      content: '是否确认收货',
      confirmColor:'#f84880',
      success:function(res){
        if(res.confirm==true){
          app.func.postReq('/text/index.php/home/productzf/confirmpro', { orderid: id }, function (res) {
            if (parseFloat(res) == 1) {
              that.setData({
                [`orders[${index}].status`]: 4,
                [`orders[${index}].time`]: ""
              })
              wx.showToast({
                title: '已签收',
                icon: 'none'
              })
              clearInterval(orders[index].timer)
              console.log('清除', orders[index].timer);
            } else {
              wx.showToast({
                title: '网络异常',
                icon: 'none'
              })
            }
          })
        }else{
          return;
        }
      }
    })    
  },
  bindToPay(e){
    console.log('好几十');
    if (!this.data.clickpay){
      return;
    }
    this.setData({
      clickpay:false
    })
    var that=this;
    var { id, index, totalprice}=e.currentTarget.dataset;
    var orders=that.data.orders;
    if(e.detail.value==0){
      // 微信支付
      console.log('纯微信支付')
      var data={};
      data.id=id;
      data.yue=2;
      app.func.postReq('/text/index.php/home/productzf/qfkorder',data,function(res){
        if (parseFloat(res) == 3 || parseFloat(res) == 4){
          wx.showModal({
            title:'商品库存不足',
            confirmText: "删除",
            content: '是否删除该订单',
            confirmColor:'#f84880',
            success:function(res){
              if(res.confirm){
                app.func.postReq('/text/index.php/Home/productzf/delorder',{orderid:id},function(res){
                  wx.showToast({
                    title: '删除成功',
                    icon:'none'
                  })
                  orders.splice(index,1);
                  that.setData({
                    orders:orders,
                    clickpay:true
                  })
                  that.onReachBottom();
                });
              }
              if(res.cancel){
                that.setData({
                  clickpay: true
                })
              }
            }
          })
        }else{
          wx.requestPayment({
            'timeStamp': res.timeStamp,
            'nonceStr': res.nonceStr,
            'package': res.package,
            'signType': 'MD5',
            'paySign': res.paySign,
            'success': function (res) {
              that.setData({
                [`orders[${index}].status`]:2,
                clickpay:true
              })
              wx.showToast({
                title: '支付成功',
                icon: 'success'
              })
            },
            'fail': function (res) {
              console.log(res, '支付失败');
              that.setData({
                clickpay: true
              })
              wx.showToast({
                title: '支付取消',
                icon: 'none'
              })
            }
          })
        }
      })
    }else{
      // 余额支付
      // 1 余额大于付款金额
      if (this.data.money>=parseFloat(totalprice)){
        // 纯余额
        wx.showModal({
          content: '是否立即支付？',
          confirmColor:'#f84880',
          success:function(res){
            if(res.confirm){
              app.func.postReq('/text/index.php/home/productzf/qfkyue', { id: id }, function (res) {
                that.setData({
                  clickpay: true
                })
                if (res == 1) {
                  wx.showToast({
                    title: '支付成功',
                    icon: 'none'
                  })
                  that.setData({
                    [`orders[${index}].status`]: 2
                  })
                } else if(res=3||res==4){
                  wx.showModal({
                    title: '商品库存不足',
                    confirmText: "删除",
                    content: '是否删除该订单',
                    confirmColor: '#f84880',
                    success: function (res) {
                      if (res.confirm) {
                        app.func.postReq('/text/index.php/Home/productzf/delorder', { orderid: id }, function (res) {
                          wx.showToast({
                            title: '删除成功',
                            icon: 'none'
                          })
                          orders.splice(index, 1);
                          that.setData({
                            orders: orders
                          })
                          that.onReachBottom();
                        });
                      }
                    }
                  })
                }else{
                  wx.showToast({
                    title: '支付失败',
                    icon: 'none'
                  })
                  console.log(res, '支付失败');
                }
              })
            }else{
              that.setData({
                clickpay: true
              })
            }
          },
          fail:function(res){
            that.setData({
              clickpay: true
            })
          }
        })
      }else{
        // 余额不足 余额+微信
        console.log('余额+微信');
        var data={};
        data.id=id;
        data.yue=1;
        app.func.postReq('/text/index.php/home/productzf/qfkorder',data,function(res){
          if(res==3||res==4){
            wx.showModal({
              title: '商品库存不足',
              content: '是否删除该订单',
              confirmText: "删除",
              confirmColor: '#f84880',
              success: function (res) {
                if (res.confirm) {
                  app.func.postReq('/text/index.php/Home/productzf/delorder', { orderid: id }, function (res) {
                    wx.showToast({
                      title: '删除成功',
                      icon: 'none'
                    })
                    orders.splice(index, 1);
                    that.setData({
                      orders: orders,
                      clickpay: true
                    })
                    that.onReachBottom();
                  });
                }
                if (res.cancel) {
                  that.setData({
                    clickpay: true
                  })
                }
              }
            })
          }else{
            wx.requestPayment({
              'timeStamp': res.timeStamp,
              'nonceStr': res.nonceStr,
              'package': res.package,
              'signType': 'MD5',
              'paySign': res.paySign,
              'success': function (res) {
                that.setData({
                  [`orders[${index}].status`]:2,
                  clickpay:true
                })
                wx.showToast({
                  title: '支付成功',
                  icon: 'success'
                })
              },
              'fail': function (res) {
                console.log(res, '支付失败');
                that.setData({
                  clickpay: true
                })
                wx.showToast({
                  title: '支付取消',
                  icon: 'none'
                })
              }
            })
          }
        })
      }
    }
  },
  bindToPay2(e){
    // 余额为0的情况直接微信支付
    console.log('哈哈');
    var that = this;
    if(!this.data.clickpay){
      return;
    }
    that.setData({
      clickpay:false
    })
    var { id, index, totalprice } = e.currentTarget.dataset;
    var orders = that.data.orders;
    app.func.postReq('/text/index.php/home/productzf/qfkorder',{id:id,yue:2},function(res){
      if(res==3||res==4){
        wx.showModal({
          title: '商品库存不足',
          content: '是否删除该订单',
          confirmColor: '#f84880',
          confirmText:"删除",
          success: function (res) {
            if (res.confirm) {
              app.func.postReq('/text/index.php/Home/productzf/delorder', { orderid: id }, function (res) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'none'
                })
                orders.splice(index, 1);
                that.setData({
                  clickpay: true,
                  orders: orders
                })
                that.onReachBottom();
              });
            }
            if (res.cancel) {
              that.setData({
                clickpay: true
              })
            }
          }
        })
      }else{
        wx.requestPayment({
          'timeStamp': res.timeStamp,
          'nonceStr': res.nonceStr,
          'package': res.package,
          'signType': 'MD5',
          'paySign': res.paySign,
          'success': function (res) {
            that.setData({
              [`orders[${index}].status`]:2,
              clickpay:true
            })
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            })
          },
          'fail': function (res) {
            console.log(res, '支付失败');
            that.setData({
              clickpay: true
            })
            wx.showToast({
              title: '支付取消',
              icon: 'none'
            })
          }
        })
      }
    })
  },
  delOrder(e){
    var that=this;
    var {id,index}=e.currentTarget.dataset;
    var orders=this.data.orders;
    wx.showModal({
      content: '您确定要删除此订单吗？',
      confirmColor:"#f84880",
      success:function(res){
        if(res.confirm){
          app.func.postReq('/text/index.php/Home/productzf/delorder', { orderid: id }, function (res) {
            wx.showToast({
              title: '删除成功',
              icon: 'none'
            })
            orders.splice(index, 1);
            that.setData({
              orders: orders,
              clickpay: true
            })
            that.onReachBottom();
          });
        }
      }
    })
  },
  onPullDownRefresh:function(){
    this.clearTimer();
    if(this.data.status){
      this.reqData11(true);
    }else{
      this.reqData1(true);
    }
  },
  onReachBottom:function(){
    if(this.data.readMore){
      this.setData({
        loadHidden:true
      })
      if(this.data.status){
        this.reqData21();
      }else{
        this.reqData2();
      }
    }
  }
})